import { useState, useEffect } from "react";
import { useTheme } from "@/hooks/useTheme";
import { Empty } from "@/components/Empty";
import { motion } from "framer-motion";
import { toast } from "sonner";

// 定义项目数据类型
interface Project {
  id: string;
  title: string;
  thumbnail: string;
  status: "draft" | "generating" | "completed" | "failed";
  createdAt: string;
  prompt?: string;
  duration?: string;
  resolution?: string;
  fps?: number;
  aspectRatio?: string;
  cameraMovement?: string;
  fileCount?: number; // 上传的文件数量
  generationTime?: number; // 生成时间（秒）
}

// Mock项目数据
const mockProjects: Project[] = [
  {
    id: "p1",
    title: "我的旅行回忆",
    thumbnail: "https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_4_3&prompt=travel%20memories%20mountain%20landscape&sign=6cb5777e1a9963bea3dbb7a6601afdd2",
    status: "completed",
    createdAt: "2025-11-18",
    prompt: "一段关于山间旅行的视频，展示壮丽的自然风光和宁静的氛围",
    duration: "02:30",
    resolution: "4K",
    fps: 24,
    aspectRatio: "16:9",
    cameraMovement: "360度环绕",
    fileCount: 2,
    generationTime: 185
  },
  {
    id: "p2",
    title: "产品宣传视频",
    thumbnail: "https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_4_3&prompt=product%20promotion%20video%20modern%20tech&sign=73af591542d1fcaf0d9576c23ce93c8f",
    status: "generating",
    createdAt: "2025-11-18",
    prompt: "为一款新型智能设备制作宣传视频，展示其设计和功能",
    resolution: "1080P",
    fps: 30,
    aspectRatio: "16:9",
    cameraMovement: "推拉",
    fileCount: 1,
    generationTime: 0
  },
  {
    id: "p3",
    title: "科幻短片创意",
    thumbnail: "https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_4_3&prompt=science%20fiction%20short%20film%20concept&sign=80257cf4c9c4a1a09607af1f4d8d8b12",
    status: "draft",
    createdAt: "2025-11-17",
    prompt: "创建一个未来城市的科幻短片，包含飞行汽车和全息投影",
    resolution: "4K",
    fps: 24,
    aspectRatio: "16:9",
    cameraMovement: "子弹时间"
  },
  {
    id: "p4",
    title: "自然纪录片",
    thumbnail: "https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_4_3&prompt=nature%20documentary%20wildlife%20river&sign=bece1b1feeb986a1ec5f868c1397e53c",
    status: "failed",
    createdAt: "2025-11-16",
    prompt: "制作一段关于河流生态系统的自然纪录片",
    resolution: "4K",
    fps: 24,
    aspectRatio: "16:9",
    cameraMovement: "固定视角",
    fileCount: 3,
    generationTime: 0
  }
];

const MyProjects = () => {
  const { isDark } = useTheme();
  const [projects, setProjects] = useState<Project[]>(mockProjects);
  const [selectedTab, setSelectedTab] = useState<string>("all");
  const [searchQuery, setSearchQuery] = useState<string>("");
  const [expandedProjectId, setExpandedProjectId] = useState<string | null>(null);

  // 从本地存储加载项目数据
  useEffect(() => {
    const savedProjects = localStorage.getItem('ai_video_projects');
    if (savedProjects) {
      try {
        setProjects(JSON.parse(savedProjects));
      } catch (e) {
        console.error('Failed to load projects from localStorage', e);
      }
    }
  }, []);

  // 保存项目数据到本地存储
  useEffect(() => {
    localStorage.setItem('ai_video_projects', JSON.stringify(projects));
  }, [projects]);

  // 根据标签和搜索过滤项目
  const filteredProjects = projects.filter(project => {
    const matchesTab = selectedTab === "all" || project.status === selectedTab;
    const matchesSearch = project.title.toLowerCase().includes(searchQuery.toLowerCase()) || 
                          (project.prompt && project.prompt.toLowerCase().includes(searchQuery.toLowerCase()));
    return matchesTab && matchesSearch;
  });

  // 删除项目
  const handleDeleteProject = (id: string) => {
    if (window.confirm("确定要删除这个项目吗？")) {
      setProjects(prevProjects => prevProjects.filter(project => project.id !== id));
      toast.success("项目已删除");
    }
  };

  // 重新生成项目
  const handleRegenerate = (id: string) => {
    setProjects(prevProjects => 
      prevProjects.map(project => 
        project.id === id ? { ...project, status: "generating" } : project
      )
    );
    toast.info("正在重新生成视频");
  };

  // 切换项目详情展开/折叠
  const toggleProjectDetails = (id: string) => {
    setExpandedProjectId(expandedProjectId === id ? null : id);
  };

  // 获取状态对应的颜色和文本
  const getStatusInfo = (status: Project["status"]) => {
    switch (status) {
      case "draft":
        return { color: "bg-yellow-500", text: "草稿" };
      case "generating":
        return { color: "bg-blue-500", text: "生成中" };
      case "completed":
        return { color: "bg-green-500", text: "已完成" };
      case "failed":
        return { color: "bg-red-500", text: "生成失败" };
      default:
        return { color: "bg-gray-500", text: "未知" };
    }
  };

  // 格式化生成时间
  const formatGenerationTime = (seconds: number): string => {
    if (seconds === 0) return "计算中...";
    
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}分${secs}秒`;
  };

  // 动画变体
  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.05
      }
    }
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 10 },
    visible: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.3
      }
    }
  };

  return (
    <div className={`min-h-screen ${isDark ? 'text-white' : 'text-slate-900'}`}>
      {/* 背景装饰 */}
      <div className={`fixed inset-0 -z-10 opacity-10 ${isDark ? 'bg-gradient-dark-ai' : 'bg-gradient-ai'}`}></div>
      
      <div className="container mx-auto max-w-6xl">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl md:text-4xl font-bold mb-2">我的项目</h1>
          <p className={`${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
            管理和查看您创建的所有AI视频项目
          </p>
        </div>

        {/* 搜索框 */}
        <div className={`relative mb-6 max-w-md ${isDark ? 'bg-slate-800' : 'bg-white'} rounded-lg shadow-md`}>
          <input
            type="text"
            placeholder="搜索项目..."
            className={`w-full pl-10 pr-4 py-2.5 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 ${isDark ? 'bg-transparent placeholder-slate-500' : 'placeholder-slate-400'}`}
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
          <i className="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400"></i>
        </div>

        {/* 项目标签 */}
        <div className="flex flex-wrap gap-2 mb-6">
          <button
            className={`px-4 py-1.5 rounded-full text-sm font-medium transition-colors duration-300 ${
              selectedTab === "all" 
                ? 'bg-indigo-600 text-white' 
                : `${isDark ? 'bg-slate-800 hover:bg-slate-700' : 'bg-white hover:bg-slate-100'} shadow-sm`
            }`}
            onClick={() => setSelectedTab("all")}
          >
            全部
          </button>
          <button
            className={`px-4 py-1.5 rounded-full text-sm font-medium transition-colors duration-300 ${
              selectedTab === "draft" 
                ? 'bg-indigo-600 text-white' 
                : `${isDark ? 'bg-slate-800 hover:bg-slate-700' : 'bg-white hover:bg-slate-100'} shadow-sm`
            }`}
            onClick={() => setSelectedTab("draft")}
          >
            草稿
          </button>
          <button
            className={`px-4 py-1.5 rounded-full text-sm font-medium transition-colors duration-300 ${
              selectedTab === "generating" 
                ? 'bg-indigo-600 text-white' 
                : `${isDark ? 'bg-slate-800 hover:bg-slate-700' : 'bg-white hover:bg-slate-100'} shadow-sm`
            }`}
            onClick={() => setSelectedTab("generating")}
          >
            生成中
          </button>
          <button
            className={`px-4 py-1.5 rounded-full text-sm font-medium transition-colors duration-300 ${
              selectedTab === "completed" 
                ? 'bg-indigo-600 text-white' 
                : `${isDark ? 'bg-slate-800 hover:bg-slate-700' : 'bg-white hover:bg-slate-100'} shadow-sm`
            }`}
            onClick={() => setSelectedTab("completed")}
          >
            已完成
          </button>
          <button
            className={`px-4 py-1.5 rounded-full text-sm font-medium transition-colors duration-300 ${
              selectedTab === "failed" 
                ? 'bg-indigo-600 text-white' 
                : `${isDark ? 'bg-slate-800 hover:bg-slate-700' : 'bg-white hover:bg-slate-100'} shadow-sm`
            }`}
            onClick={() => setSelectedTab("failed")}
          >
            生成失败
          </button>
        </div>

        {/* 项目列表 */}
        {filteredProjects.length > 0 ? (
          <motion.div 
            className="space-y-4"
            variants={containerVariants}
            initial="hidden"
            animate="visible"
          >
            {filteredProjects.map(project => {
              const statusInfo = getStatusInfo(project.status);
              
              return (
                <motion.div
                  key={project.id}
                  variants={itemVariants}
                  className={`rounded-xl overflow-hidden ${isDark ? 'bg-slate-800' : 'bg-white'} shadow-lg transition-all duration-300 hover:shadow-xl`}
                >
                  <div className="flex flex-col md:flex-row">
                    {/* 缩略图 */}
                    <div className="md:w-1/3 aspect-video md:aspect-auto">
                      <img 
                        src={project.thumbnail} 
                        alt={project.title}
                        className="w-full h-full object-cover"
                      />
                      
                      {/* HunyuanVideo生成标记 */}
                      {project.status === "completed" && (
                        <div className="absolute bottom-2 left-2 bg-gradient-to-r from-indigo-600 to-purple-600 text-white text-xs px-2 py-1 rounded-full">
                          <i className="fa-solid fa-robot mr-1"></i>Hunyuan生成
                        </div>
                      )}
                    </div>
                    
                    {/* 项目信息 */}
                    <div className="p-4 md:p-6 md:w-2/3 flex flex-col justify-between relative">
                      <div>
                        <div className="flex items-center justify-between mb-2">
                          <h3 className="text-xl font-semibold">{project.title}</h3>
                          <span className={`px-2 py-1 text-xs font-medium rounded-full ${statusInfo.color} text-white`}>
                            {statusInfo.text}
                          </span>
                        </div>
                        
                        {project.prompt && (
                          <p className={`mb-4 ${isDark ? 'text-slate-400' : 'text-slate-600'} line-clamp-2`}>
                            {project.prompt}
                          </p>
                        )}
                        
                        <div className="flex flex-wrap items-center text-sm mb-4 gap-x-4 gap-y-2">
                          <span className={`${isDark ? 'text-slate-400' : 'text-slate-500'}`}>
                            创建于: {project.createdAt}
                          </span>
                          {project.duration && (
                            <span className={`${isDark ? 'text-slate-400' : 'text-slate-500'}`}>
                              时长: {project.duration}
                            </span>
                          )}
                          {project.resolution && (
                            <span className={`${isDark ? 'text-slate-400' : 'text-slate-500'}`}>
                              分辨率: {project.resolution}
                            </span>
                          )}
                          {project.fps && (
                            <span className={`${isDark ? 'text-slate-400' : 'text-slate-500'}`}>
                              帧率: {project.fps} FPS
                            </span>
                          )}
                        </div>
                        
                        {/* 展开的详细信息 */}
                        {expandedProjectId === project.id && (
                          <motion.div 
                            initial={{ opacity: 0, height: 0 }}
                            animate={{ opacity: 1, height: "auto" }}
                            exit={{ opacity: 0, height: 0 }}
                            className={`p-4 rounded-lg mb-4 ${isDark ? 'bg-slate-700/50' : 'bg-slate-100/80'}`}
                          >
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                              <div>
                                <h4 className="text-sm font-medium mb-2">技术信息</h4>
                                <ul className="text-sm space-y-1">
                                  <li className={`${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
                                    <i className="fa-solid fa-film mr-1"></i> 视频比例: {project.aspectRatio || '16:9'}
                                  </li>
                                  <li className={`${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
                                    <i className="fa-solid fa-arrows-rotate mr-1"></i> 运镜方式: {project.cameraMovement || '固定视角'}
                                  </li>
                                  <li className={`${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
                                    <i className="fa-solid fa-file-image mr-1"></i> 参考文件: {project.fileCount || 0} 个
                                  </li>
                                  <li className={`${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
                                    <i className="fa-solid fa-bolt mr-1"></i> 生成时间: {formatGenerationTime(project.generationTime || 0)}
                                  </li>
                                  <li className={`${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
                                    <i className="fa-solid fa-microchip mr-1"></i> 模型优化: FP8量化推理
                                  </li>
                                </ul>
                              </div>
                              <div>
                                <h4 className="text-sm font-medium mb-2">存储信息</h4>
                                <ul className="text-sm space-y-1">
                                  <li className={`${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
                                    <i className="fa-solid fa-cloud mr-1"></i> 存储位置: 腾讯云COS
                                  </li>
                                  <li className={`${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
                                    <i className="fa-solid fa-shield-halved mr-1"></i> 安全状态: 已加密
                                  </li>
                                  {project.status === "completed" && (
                                    <li className={`${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
                                      <i className="fa-solid fa-globe mr-1"></i> 访问链接: <a href="#" className="text-indigo-500 hover:underline">查看</a>
                                    </li>
                                  )}
                                </ul>
                              </div>
                            </div>
                          </motion.div>
                        )}
                      </div>
                      
                      {/* 操作按钮 */}
                      <div className="flex justify-end space-x-3">
                        <button 
                          className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors duration-300 ${
                            isDark 
                              ? 'bg-slate-700 hover:bg-slate-600' 
                              : 'bg-slate-100 hover:bg-slate-200'
                          }`}
                          onClick={() => toggleProjectDetails(project.id)}
                        >
                          <i className={`fa-solid ${expandedProjectId === project.id ? 'fa-chevron-up' : 'fa-chevron-down'} mr-1.5`}></i>
                          {expandedProjectId === project.id ? '收起详情' : '查看详情'}
                        </button>
                        
                        <button 
                          className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors duration-300 ${
                            isDark 
                              ? 'bg-slate-700 hover:bg-slate-600' 
                              : 'bg-slate-100 hover:bg-slate-200'
                          }`}
                        >
                          <i className="fa-solid fa-pen-to-square mr-1.5"></i>编辑
                        </button>
                        
                        {project.status === "generating" && (
                          <div className={`w-32 h-2 rounded-full overflow-hidden ${isDark ? 'bg-slate-700' : 'bg-slate-200'} self-center`}>
                            <div className="h-full bg-gradient-to-r from-indigo-500 to-purple-500 animate-progress rounded-full"></div>
                          </div>
                        )}
                        
                        {project.status === "completed" && (
                          <button 
                            className={`px-4 py-2 rounded-lg text-sm font-medium bg-indigo-600 hover:bg-indigo-700 text-white transition-colors duration-300`}
                          >
                            <i className="fa-solid fa-play mr-1.5"></i>播放</button>
                        )}
                        
                        {project.status === "failed" && (
                          <button 
                            className={`px-4 py-2 rounded-lg text-sm font-medium bg-green-600 hover:bg-green-700 text-white transition-colors duration-300`}
                            onClick={() => handleRegenerate(project.id)}
                          >
                            <i className="fa-solid fa-rotate-right mr-1.5"></i>重试
                          </button>
                        )}
                        
                        <button 
                          className={`p-2 rounded-lg text-sm font-medium transition-colors duration-300 ${
                            isDark 
                              ? 'hover:bg-red-900/30 text-red-500' 
                              : 'hover:bg-red-100 text-red-500'
                          }`}
                          onClick={() => handleDeleteProject(project.id)}
                          aria-label="删除项目"
                        >
                          <i className="fa-solid fa-trash-can"></i>
                        </button>
                      </div>
                    </div>
                  </div>
                </motion.div>
              );
            })}
          </motion.div>
        ) : (
          <Empty message="没有找到匹配的项目" />
        )}

        {/* 创建新项目按钮 */}
        <div className="mt-10 text-center">
          <a 
            href="/#generator" 
            className="inline-flex items-center px-6 py-3 rounded-full bg-gradient-to-r from-indigo-600 to-purple-600 text-white font-medium shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1"
          >
            <i className="fa-solid fa-plus mr-2"></i>
            创建新项目
          </a>
        </div>
      </div>
    </div>
  );
};

export default MyProjects;